<template>
  <div class="scholarship-container">
    <h2>{{ getPageTitle() }}</h2>
    
    <el-tabs v-model="activeTab">
      <el-tab-pane :label="getTabLabel('available')" name="available">
        <el-row :gutter="20">
          <el-col :span="8" v-for="scholarship in availableScholarships" :key="scholarship.id">
            <el-card class="scholarship-card" shadow="hover">
              <div class="scholarship-header">
                <h3>{{ scholarship.name }}</h3>
                <el-tag :type="scholarship.level === '国家级' ? 'danger' : scholarship.level === '省级' ? 'warning' : 'primary'">
                  {{ scholarship.level }}
                </el-tag>
              </div>
              <div class="scholarship-amount">
                奖金：<span class="amount">¥{{ scholarship.amount }}</span>
              </div>
              <div class="scholarship-deadline">
                截止日期：<span class="deadline">{{ scholarship.deadline }}</span>
              </div>
              <div class="scholarship-description">
                {{ scholarship.description }}
              </div>
              <div class="scholarship-actions">
                <el-button v-if="userRole === 'student'" type="primary" @click="applyForScholarship(scholarship)">申报</el-button>
                <el-button v-if="userRole === 'teacher' || userRole === 'principal'" type="primary" @click="reviewScholarship(scholarship)">{{ userRole === 'teacher' ? '审批' : '终审' }}</el-button>
                <el-button @click="viewScholarshipDetail(scholarship)">详情</el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <el-empty v-if="availableScholarships.length === 0" description="暂无奖学金项目" />
      </el-tab-pane>
      
      <el-tab-pane :label="getTabLabel('myApplications')" name="myApplications">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>{{ getRecordTitle() }}</span>
              <el-button @click="refreshApplications">刷新</el-button>
            </div>
          </template>
          
          <el-table :data="myApplications" style="width: 100%" v-loading="loading">
            <el-table-column prop="scholarshipName" label="奖学金名称" show-overflow-tooltip></el-table-column>
            <el-table-column :prop="getApplicationColumnProp()" :label="getApplicationColumnLabel()" width="180"></el-table-column>
            <el-table-column prop="amount" label="奖金" width="120">
              <template #default="scope">
                ¥{{ scope.row.amount }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="viewApplicationDetail(scope.row)">详情</el-button>
                <el-button 
                  v-if="userRole === 'student' && scope.row.status === '待提交'" 
                  size="small" 
                  type="danger" 
                  @click="cancelApplication(scope.row)">
                  撤销
                </el-button>
                <el-button 
                  v-if="(userRole === 'teacher' && (scope.row.status === '待审批' || scope.row.status === '学院审核')) || 
                        (userRole === 'principal' && scope.row.status === '待终审')" 
                  size="small" 
                  type="primary" 
                  @click="approveApplication(scope.row)">
                  {{ userRole === 'teacher' ? '审批' : '终审' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            @current-change="handlePageChange"
            class="pagination">
          </el-pagination>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane :label="getTabLabel('progress')" name="progress">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>{{ getProgressTitle() }}</span>
              <el-button @click="refreshProgress">刷新</el-button>
            </div>
          </template>
          
          <el-timeline v-loading="progressLoading">
            <el-timeline-item
              v-for="(activity, index) in progressActivities"
              :key="index"
              :timestamp="activity.timestamp"
              :type="activity.type"
              :color="activity.color">
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 奖学金详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="selectedScholarship.name" width="50%">
      <el-form :model="selectedScholarship" label-width="100px">
        <el-form-item label="奖学金名称:">
          <span>{{ selectedScholarship.name }}</span>
        </el-form-item>
        <el-form-item label="级别:">
          <el-tag :type="selectedScholarship.level === '国家级' ? 'danger' : selectedScholarship.level === '省级' ? 'warning' : 'primary'">
            {{ selectedScholarship.level }}
          </el-tag>
        </el-form-item>
        <el-form-item label="奖金:">
          <span class="amount">¥{{ selectedScholarship.amount }}</span>
        </el-form-item>
        <el-form-item label="申报条件:">
          <div v-html="selectedScholarship.conditions"></div>
        </el-form-item>
        <el-form-item label="截止日期:">
          <span class="deadline">{{ selectedScholarship.deadline }}</span>
        </el-form-item>
        <el-form-item label="申请材料:">
          <div v-html="selectedScholarship.materials"></div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button v-if="userRole === 'student'" type="primary" @click="applyForScholarship(selectedScholarship)">申报</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 申报表单对话框 -->
    <el-dialog v-model="applyDialogVisible" title="奖学金申报" width="60%" v-if="userRole === 'student'">
      <el-form :model="applicationForm" :rules="applyRules" ref="applyForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="奖学金名称">
              <el-input v-model="applicationForm.scholarshipName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申报日期">
              <el-date-picker
                v-model="applicationForm.applyDate"
                type="date"
                placeholder="选择日期"
                disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="个人基本信息">
          <el-card>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="applicationForm.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="学号" prop="studentId">
                  <el-input v-model="applicationForm.studentId"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="专业" prop="major">
                  <el-input v-model="applicationForm.major"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="applicationForm.phone"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form-item>
        
        <el-form-item label="学习成绩">
          <el-card>
            <el-table :data="applicationForm.grades" style="width: 100%">
              <el-table-column prop="subject" label="科目">
                <template #default="scope">
                  <el-input v-model="scope.row.subject"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="credit" label="学分">
                <template #default="scope">
                  <el-input v-model="scope.row.credit"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="score" label="成绩">
                <template #default="scope">
                  <el-input v-model="scope.row.score"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="scope">
                  <el-button @click="removeGrade(scope.$index)" type="danger" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px;">
              <el-button @click="addGrade" type="primary" size="small">添加科目</el-button>
            </div>
          </el-card>
        </el-form-item>
        
        <el-form-item label="获奖经历">
          <el-card>
            <el-table :data="applicationForm.awards" style="width: 100%">
              <el-table-column prop="name" label="奖项名称">
                <template #default="scope">
                  <el-input v-model="scope.row.name"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="level" label="级别">
                <template #default="scope">
                  <el-input v-model="scope.row.level"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="date" label="获奖时间">
                <template #default="scope">
                  <el-date-picker v-model="scope.row.date" type="date" placeholder="选择日期"></el-date-picker>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="scope">
                  <el-button @click="removeAward(scope.$index)" type="danger" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px;">
              <el-button @click="addAward" type="primary" size="small">添加奖项</el-button>
            </div>
          </el-card>
        </el-form-item>
        
        <el-form-item label="证明材料">
          <el-upload
            v-model:file-list="applicationForm.files"
            class="upload-demo"
            action="/api/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="5"
            :on-exceed="handleExceed"
            multiple>
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png/pdf/doc等格式，单个文件不超过10MB，最多上传5个文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="applyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitApplication">提交</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 审批对话框 -->
    <el-dialog v-model="reviewDialogVisible" :title="getReviewDialogTitle()" width="50%" v-if="userRole === 'teacher' || userRole === 'principal'">
      <el-form :model="reviewForm" label-width="100px">
        <el-form-item label="奖学金名称:">
          <span>{{ reviewForm.scholarshipName }}</span>
        </el-form-item>
        <el-form-item label="申请人:">
          <span>{{ reviewForm.studentName }}</span>
        </el-form-item>
        <el-form-item label="申请时间:">
          <span>{{ reviewForm.applyDate }}</span>
        </el-form-item>
        <el-form-item label="审批意见:">
          <el-input
            v-model="reviewForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见">
          </el-input>
        </el-form-item>
        <el-form-item label="审批结果:">
          <el-radio-group v-model="reviewForm.result">
            <el-radio label="通过">通过</el-radio>
            <el-radio label="不通过">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview">提交审批</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Scholarship',
  data() {
    return {
      userRole: 'student', // 默认为学生
      activeTab: 'available',
      loading: false,
      progressLoading: false,
      availableScholarships: [
        {
          id: 1,
          name: '国家奖学金',
          level: '国家级',
          amount: 8000,
          deadline: '2024-11-15',
          description: '用于奖励特别优秀的全日制本专科学生',
          conditions: '<p>1. 热爱社会主义祖国，拥护中国共产党的领导<br>2. 遵守宪法和法律，遵守学校规章制度<br>3. 诚实守信，道德品质优良<br>4. 在校期间学习成绩优异，社会实践、创新能力、综合素质等方面特别突出</p>',
          materials: '<p>1. 奖学金申请审批表<br>2. 学习成绩单<br>3. 获奖证书复印件<br>4. 其他相关证明材料</p>'
        },
        {
          id: 2,
          name: '学业奖学金',
          level: '校级',
          amount: 3000,
          deadline: '2024-11-30',
          description: '用于奖励学习成绩优秀的学生',
          conditions: '<p>1. 热爱社会主义祖国，拥护中国共产党的领导<br>2. 遵守宪法和法律，遵守学校规章制度<br>3. 诚实守信，道德品质优良<br>4. 学习成绩排名在前30%</p>',
          materials: '<p>1. 奖学金申请表<br>2. 学习成绩单<br>3. 其他相关证明材料</p>'
        },
        {
          id: 3,
          name: '励志奖学金',
          level: '国家级',
          amount: 5000,
          deadline: '2024-11-10',
          description: '用于奖励资助品学兼优的家庭经济困难学生',
          conditions: '<p>1. 热爱社会主义祖国，拥护中国共产党的领导<br>2. 遵守宪法和法律，遵守学校规章制度<br>3. 诚实守信，道德品质优良<br>4. 家庭经济困难，生活俭朴<br>5. 学习成绩优秀</p>',
          materials: '<p>1. 奖学金申请审批表<br>2. 学习成绩单<br>3. 家庭经济困难证明<br>4. 获奖证书复印件<br>5. 其他相关证明材料</p>'
        }
      ],
      myApplications: [
        {
          id: 1,
          scholarshipName: '国家奖学金',
          applyDate: '2024-10-20',
          studentName: '张三',
          amount: 8000,
          status: '审核中'
        },
        {
          id: 2,
          scholarshipName: '学业奖学金',
          applyDate: '2024-10-15',
          studentName: '李四',
          amount: 3000,
          status: '已通过'
        }
      ],
      total: 100,
      pageSize: 10,
      currentPage: 1,
      detailDialogVisible: false,
      applyDialogVisible: false,
      reviewDialogVisible: false,
      selectedScholarship: {},
      applicationForm: {
        scholarshipName: '',
        applyDate: '',
        name: '',
        studentId: '',
        major: '',
        phone: '',
        grades: [
          { subject: '', credit: '', score: '' }
        ],
        awards: [
          { name: '', level: '', date: '' }
        ],
        files: []
      },
      reviewForm: {
        scholarshipName: '',
        studentName: '',
        applyDate: '',
        comment: '',
        result: '通过'
      },
      applyRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        studentId: [
          { required: true, message: '请输入学号', trigger: 'blur' }
        ],
        major: [
          { required: true, message: '请输入专业', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ]
      },
      progressActivities: [
        {
          timestamp: '2024-10-20',
          content: '提交国家奖学金申请',
          type: 'primary',
          color: '#409eff'
        },
        {
          timestamp: '2024-10-21',
          content: '学院审核通过',
          type: 'success',
          color: '#67c23a'
        },
        {
          timestamp: '2024-10-25',
          content: '学校复审中',
          type: 'warning',
          color: '#e6a23c'
        }
      ]
    }
  },
  mounted() {
    // 获取用户角色
    const userStr = localStorage.getItem('user')
    if (userStr) {
      try {
        const user = JSON.parse(userStr)
        this.userRole = user.role
      } catch (e) {
        console.error('解析用户信息失败:', e)
      }
    }
  },
  methods: {
    getPageTitle() {
      switch (this.userRole) {
        case 'student':
          return '奖学金申报'
        case 'teacher':
          return '奖学金审批'
        case 'principal':
          return '奖学金终审'
        default:
          return '奖学金'
      }
    },
    getTabLabel(tab) {
      if (tab === 'available') {
        switch (this.userRole) {
          case 'student':
            return '可申报项目'
          case 'teacher':
            return '待审批项目'
          case 'principal':
            return '待终审项目'
          default:
            return '项目'
        }
      } else if (tab === 'myApplications') {
        switch (this.userRole) {
          case 'student':
            return '我的申报'
          case 'teacher':
            return '审批记录'
          case 'principal':
            return '终审记录'
          default:
            return '记录'
        }
      } else {
        switch (this.userRole) {
          case 'student':
            return '申报进度'
          case 'teacher':
            return '审批进度'
          case 'principal':
            return '终审进度'
          default:
            return '进度'
        }
      }
    },
    getRecordTitle() {
      switch (this.userRole) {
        case 'student':
          return '申报记录'
        case 'teacher':
          return '审批记录'
        case 'principal':
          return '终审记录'
        default:
          return '记录'
      }
    },
    getProgressTitle() {
      switch (this.userRole) {
        case 'student':
          return '审核进度'
        case 'teacher':
          return '审批进度'
        case 'principal':
          return '终审进度'
        default:
          return '进度'
      }
    },
    getApplicationColumnProp() {
      switch (this.userRole) {
        case 'student':
          return 'applyDate'
        case 'teacher':
        case 'principal':
          return 'studentName'
        default:
          return 'applyDate'
      }
    },
    getApplicationColumnLabel() {
      switch (this.userRole) {
        case 'student':
          return '申报日期'
        case 'teacher':
        case 'principal':
          return '学生姓名'
        default:
          return '日期'
      }
    },
    getReviewDialogTitle() {
      switch (this.userRole) {
        case 'teacher':
          return '奖学金审批'
        case 'principal':
          return '奖学金终审'
        default:
          return '审批'
      }
    },
    viewScholarshipDetail(scholarship) {
      this.selectedScholarship = scholarship
      this.detailDialogVisible = true
    },
    applyForScholarship(scholarship) {
      if (this.userRole !== 'student') return
      this.selectedScholarship = scholarship
      this.applicationForm.scholarshipName = scholarship.name
      this.applicationForm.applyDate = new Date().toISOString().slice(0, 10)
      this.applyDialogVisible = true
    },
    reviewScholarship(scholarship) {
      if (this.userRole !== 'teacher' && this.userRole !== 'principal') return
      this.selectedScholarship = scholarship
      this.reviewForm.scholarshipName = scholarship.name
      this.reviewForm.studentName = '张三' // 示例数据
      this.reviewForm.applyDate = '2024-10-20' // 示例数据
      this.reviewDialogVisible = true
    },
    refreshApplications() {
      this.loading = true
      // 模拟刷新数据
      setTimeout(() => {
        this.loading = false
        this.$message.success('刷新成功')
      }, 500)
    },
    handlePageChange(page) {
      this.currentPage = page
      this.loading = true
      // 模拟分页加载
      setTimeout(() => {
        this.loading = false
      }, 500)
    },
    getStatusType(status) {
      const statusMap = {
        '待提交': 'info',
        '审核中': 'warning',
        '已通过': 'success',
        '未通过': 'danger',
        '待审批': 'warning',
        '学院审核': 'warning',
        '待终审': 'warning'
      }
      return statusMap[status] || 'info'
    },
    viewApplicationDetail(application) {
      this.$message.info(`查看${this.userRole === 'student' ? '申请' : '审批'}详情: ${application.scholarshipName}`)
    },
    cancelApplication(application) {
      this.$confirm(`确定要撤销《${application.scholarshipName}》的申请吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('申请已撤销')
      }).catch(() => {
        // 取消操作
      })
    },
    approveApplication(application) {
      if (this.userRole !== 'teacher' && this.userRole !== 'principal') return
      this.reviewForm.scholarshipName = application.scholarshipName
      this.reviewForm.studentName = application.studentName
      this.reviewForm.applyDate = application.applyDate
      this.reviewDialogVisible = true
    },
    refreshProgress() {
      this.progressLoading = true
      // 模拟刷新数据
      setTimeout(() => {
        this.progressLoading = false
        this.$message.success('刷新成功')
      }, 500)
    },
    addGrade() {
      this.applicationForm.grades.push({ subject: '', credit: '', score: '' })
    },
    removeGrade(index) {
      if (this.applicationForm.grades.length <= 1) {
        this.$message.warning('至少保留一行')
        return
      }
      this.applicationForm.grades.splice(index, 1)
    },
    addAward() {
      this.applicationForm.awards.push({ name: '', level: '', date: '' })
    },
    removeAward(index) {
      if (this.applicationForm.awards.length <= 1) {
        this.$message.warning('至少保留一行')
        return
      }
      this.applicationForm.awards.splice(index, 1)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    beforeRemove(uploadFile, uploadFiles) {
      return this.$confirm(`确定移除 ${uploadFile.name}？`)
    },
    handleExceed(files, fileList) {
      this.$message.warning('最多只能上传5个文件')
    },
    submitApplication() {
      this.$refs.applyForm.validate((valid) => {
        if (valid) {
          this.$message.success('申请提交成功，请等待审核！')
          this.applyDialogVisible = false
        } else {
          this.$message.error('请完善申请信息')
          return false
        }
      })
    },
    submitReview() {
      this.$message.success(`${this.userRole === 'teacher' ? '审批' : '终审'}已提交，结果：${this.reviewForm.result}`)
      this.reviewDialogVisible = false
    }
  }
}
</script>

<style scoped>
.scholarship-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.scholarship-card {
  margin-bottom: 20px;
}

.scholarship-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.scholarship-header h3 {
  margin: 0;
  color: #303133;
}

.scholarship-amount,
.scholarship-deadline {
  margin-bottom: 10px;
  font-size: 14px;
}

.amount {
  color: #e6a23c;
  font-weight: bold;
  font-size: 16px;
}

.deadline {
  color: #f56c6c;
  font-weight: bold;
}

.scholarship-description {
  margin-bottom: 15px;
  color: #606266;
  line-height: 1.5;
}

.scholarship-actions {
  text-align: right;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>